package cn.virens.common.boot.seata;

import cn.virens.common.util.exception.APIException;
import org.apache.seata.common.executor.Initialize;
import org.apache.seata.common.loader.LoadLevel;
import org.apache.seata.rm.datasource.undo.BranchUndoLog;
import org.apache.seata.rm.datasource.undo.UndoLogParser;
import org.dromara.hutool.core.io.SerializeUtil;

@LoadLevel(name = JdkUndoLogParser.NAME)
public class JdkUndoLogParser implements UndoLogParser, Initialize {
    private static final byte[] DEF_CONTENT = new byte[]{};

    public static final String NAME = "jdk";

    @Override
    public void init() {
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public byte[] getDefaultContent() {
        return DEF_CONTENT;
    }

    @Override
    public byte[] encode(BranchUndoLog branchUndoLog) {
        return SerializeUtil.serialize(branchUndoLog);
    }

    @Override
    public BranchUndoLog decode(byte[] bytes) throws APIException {
        if (bytes != null && bytes.length > 0 && bytes != DEF_CONTENT) {
            return SerializeUtil.deserialize(bytes);
        } else {
            return null;
        }
    }
}
